package vn.ebuzz.sms.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import vn.ebuzz.sms.core.Configuration;
import vn.ebuzz.sms.core.Database;
import vn.ebuzz.sms.core.Util;

public class MTServlet extends HttpServlet {
	private static Logger log = Logger.getLogger("endpoint");
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		String sender = request.getParameter("sender");
		String receiver = request.getParameter("receiver");
		String message = request.getParameter("message");
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
		String url = request.getParameter("url");
		
		PrintWriter out = response.getWriter();
		if(!Util.isValidParam(sender) 
				|| !Util.isValidParam(id)
				|| !Util.isValidParam(receiver)
				|| !Util.isValidParam(message)
				|| !Util.isValidParam(pw)){
			String result = "Missing param";
			out.print(Configuration.MT_PUSH_PARAM +"|" + result);
			log.info("MT: " + result);
			return;
		}
		if(!Configuration.MDOORPW.equals(pw)){
			String result = "Wrong password";
			out.print(Configuration.MT_PUSH_PASSWORD +"|" + result);
			log.info("MT: " + result);
			return;
		}

		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;

		boolean isExist = false;
		String mo_id = null;
		String session_id = null;
		String unique_id = null;
		try{
			conn = Database.getConnection();
			st = conn.createStatement();
			String sql = "select unique_id, mo_id, session_id" +
			" from incoming" +
			" where id = " + id;
			rs = st.executeQuery(sql);
			while(rs.next()){
				mo_id = rs.getString("mo_id");
				session_id = rs.getString("session_id");
				unique_id = rs.getString("unique_id");
				isExist = true;
				break;
			}
		} catch(Exception e){
			log.error("Error", e);
		} finally {
			if (st != null) {
				try {
					st.close();
				} catch (SQLException e) {
					log.error("Error", e);
				}
			}
			if (conn != null) {
				Database.closeConnection(conn);
			}			
		}

		if(isExist){
			new Thread(new InsertTask(id, sender, receiver,
					message, mo_id, session_id, unique_id, url)).start();
			String result = "MT accepted";
			out.print(Configuration.MT_PUSH_ACCEPT +"|" + result);
			log.info("MT: " + result);		
		}
		else{
			String result = "MT unaccepted";
			out.print(Configuration.MT_PUSH_UNACCEPT +"|" + result);
			log.info("MT: " + result);			
		}
	}

	class InsertTask implements Runnable{
		private String sender;
		private String receiver;
		private String message;
		private String mo_id;
		private String session_id;
		private String unique_id;
		private String id;
		private String url;
		private int type = 0;
		public InsertTask(String id, String sender, String receiver,
				String message, String mo_id, String session_id, String unique_id, String url){
			this.id = id;
			this.sender = sender;
			this.receiver = receiver;
			this.message = message;
			this.mo_id = mo_id;
			this.session_id = session_id;
			this.unique_id = unique_id;
			if(url != null){
				this.url = url;
				this.type = 1;
			}
		}

		public void run() {
			Connection conn = null;
			PreparedStatement preparedStatement = null;
			try {
				String sql = "insert into outgoing" +
				" (sender, receiver, message, status," +
				" incoming_id, mo_id, session_id, unique_id," +
				" result, mtcount, mostatus, type, url) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";

				conn = Database.getConnection();
				preparedStatement = conn.prepareStatement(sql);
				preparedStatement.setString(1, sender);
				preparedStatement.setString(2, receiver);
				preparedStatement.setString(3, message);
				preparedStatement.setInt(4, Configuration.MT_QUEUED);
				preparedStatement.setInt(5, Integer.parseInt(id));
				preparedStatement.setString(6, mo_id);
				preparedStatement.setString(7, session_id);
				preparedStatement.setString(8, unique_id);
				preparedStatement.setString(9, "");
				preparedStatement.setInt(10, Util.countLength(message));
				preparedStatement.setInt(11, Configuration.MO_FINISHED);
				preparedStatement.setInt(12, type);
				preparedStatement.setString(13, url);
				preparedStatement.execute();
			} catch (SQLException e) {
				log.error("Error", e);
			} finally {
				if (preparedStatement != null) {
					try {
						preparedStatement.close();
					} catch (SQLException e) {
						log.error("Error", e);
					}
				}
				if (conn != null) {
					Database.closeConnection(conn);
				}
			}			
		}					
	}
}
